package xing.application.service.isv.suite;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xing.application.api.DingApi;
import xing.application.service.BaseService;
import xing.domain.isv.suite.CorpToken;
import xing.infrastructure.util.IdWorker;
import xing.repository.isv.suite.CorpSuiteAuthRepository;
import xing.repository.isv.suite.CorpTokenRepository;
import xing.repository.isv.suite.SuiteTokenRepository;

import java.util.Calendar;
import java.util.Date;

/********************************
 * 文 件 名 :CorpTokenService.java
 * 创 建 人：陈天龙
 * 日    期：2017/8/25
 * 描   述：CorpToken业务操作
 * 版 本 号：v1.0.0
 ********************************/
@Service
public class CorpTokenService extends BaseService {

    @Autowired
    private CorpTokenRepository corpTokenRepository;
    @Autowired
    private SuiteTokenRepository suiteTokenRepository;
    @Autowired
    private CorpSuiteAuthRepository corpSuiteAuthRepository;
    @Autowired
    private DingApi dingApi;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 描    述：获取corpToken
     * 创 建 人：陈天龙
     * 日    期：2017/8/25
     * @param suiteKey
     * @param corpId
     * @return CorpToken
     */
    @Transactional(rollbackFor = Exception.class)
    public CorpToken getCorpToken(String suiteKey, String corpId) throws Exception{
        logger.info("suiteKey:{},corpId:{}",suiteKey,corpId);
        CorpToken corpToken = corpTokenRepository.findBySuiteKeyAndCorpId(suiteKey,corpId);
        //如果过期重新请求
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, 10);//为了防止误差,提前10分钟更新corptoken
        if (null == corpToken || calendar.getTime().compareTo(corpToken.getExpiredTime()) != -1) {
            CorpToken corpTokenVo = new CorpToken();
            String suiteToken = suiteTokenRepository.findSuiteTokenBySuiteKey(suiteKey);
            String permanentCode = corpSuiteAuthRepository.findByCorpIdAndSuiteKey(corpId,suiteKey).getPermanentCode();
            String res = dingApi.getCorpToken(suiteToken,corpId,permanentCode);
            logger.info("corpToken为"+res);
            JSONObject jsonObject = JSON.parseObject(res);
            corpTokenVo.setId(IdWorker.nextId());
            corpTokenVo.setCorpId(corpId);
            corpTokenVo.setSuiteKey(suiteKey);
            corpTokenVo.setCorpToken(jsonObject.getString("access_token"));
            calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.SECOND, jsonObject.getInteger("expires_in"));
            corpTokenVo.setExpiredTime(calendar.getTime());
            saveOrUpdateCorpToken(corpTokenVo);
            corpToken = corpTokenVo;
        }
        return corpToken;
    }

    /**
     * 描    述：新增或更新CorpToken
     * 创 建 人：陈天龙
     * 日    期：2017/8/25
     * @param corpToken
     */
    private void saveOrUpdateCorpToken(CorpToken corpToken)throws Exception{
        corpTokenRepository.saveOrUpdateCorpToken(corpToken.getId(),corpToken.getSuiteKey(),corpToken.getCorpId(),corpToken.getCorpToken(),corpToken.getExpiredTime());
    }
}
